package yxy.cherry.paycenter.servlet.channel.jh;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import yxy.apple.logger.Logger;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.charge;
import yxy.cherry.game.base.bean.SDKParm;
import yxy.cherry.game.base.bean.SdkParmEnum;
import yxy.cherry.paycenter.channelmodule.ActType;
import yxy.cherry.paycenter.channelmodule.sdk_jh.PayMoudle_jh;
import yxy.cherry.paycenter.database.dao.orderinfoDao;
import yxy.cherry.paycenter.database.dao.ordersDao;
import yxy.cherry.paycenter.database.db.orderinfo;
import yxy.cherry.paycenter.database.db.orders;
import yxy.cherry.paycenter.servlet.channel.Servlet;
import yxy.cherry.paycenter.util.HttpUtil;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.module.OrderInfoModule;

public class Servlet_jh extends Servlet {

	private static final Logger logger = Logger.create(Servlet_jh.class);
	
	private static final int success = 1;	//交易结果 成功
	private static final int fail = 2;	//交易结果 失败
	
	public Servlet_jh() {
//		SdkService.getInstance().addServlet("/jh", new Servlet_jh());
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpUtil.printlnParseMap("post", req);
		
//		请求参数
//		参数 		类型 	必填 参与签名 	备注 
//		appId 		String 	Y 				商户在支付平台申请的应用ID 
//		payNo 		String 	Y 				支付平台的交易订单号 
//		orderNo 	String 	Y 	Y 			商户的订单号 
//		userName 	String 	Y 	Y 			用户名称 
//		result 		int 	Y 	Y 			交易结果 1 表示成功，2 表示失败 
//		pay_channel String 	Y 	Y 			值由 orderType 决定，orderType=1 时为支 付简码；
//											orderType=2 时为渠道简码。具体 参看附录 
//		amount 		String 	Y 	Y 			支付金额（单位元） 
//		pay_time 	String 	Y 	Y 			支付时间，格式 yyyy-MM-dd HH:mm:ss 
//		userpara 	String 	Y 				透传参数，原样回传 
//		orderType 	int 	Y 				订单类型：1 平台订单；2 联运渠道订单 
//		sign 		String 	Y 				签名，具体参看签名算法说明

		JSONObject json = HttpUtil.getParseJSON(req);
		
		String appId = json.getString("appId");
		String payNo = json.getString("payNo");
		String orderNo = json.getString("orderNo");
		String userName = json.getString("userName");
		int result = json.getIntValue("result");
		String pay_channel = json.getString("pay_channel");
		String amount = json.getString("amount");
		String pay_time = json.getString("pay_time");
		String userpara = json.getString("userpara");
		int orderType = json.getIntValue("orderType");
		String sign = json.getString("sign");
		
		//myorderid 为空
		if(orderNo != null && !orderNo.equals("")) {
			orderinfo oinfo = new orderinfo();
			oinfo.setMyorderid(orderNo);
			oinfo.setOtherinfo(json.toString());
			orderinfoDao.add(oinfo);
		}
		
		String openkey = "";
		String gfappid = SDKParm.getSdkparmvalue(SdkParmEnum.jh_guanfangmubao_appid);
		String lyappid = SDKParm.getSdkparmvalue(SdkParmEnum.jh_lianyunmubao_appid);
		//核对是江湖官方母包 还是 江湖联运母包
		if(!appId.equals(gfappid) && !appId.equals(lyappid)) {
			//appid不对
			logger.info("sdk_jh appid error " + orderNo);
			returnInfo("fail", resp);
			return;
		}else {
			if(appId.equals(gfappid)) {
				openkey = SDKParm.getSdkparmvalue(SdkParmEnum.jh_guanfangmubao_openkey);
			}
			
			if(appId.equals(lyappid)) {
				openkey = SDKParm.getSdkparmvalue(SdkParmEnum.jh_lianyumgmubao_openkey);
			}
		}
		
//		if(!appId.equals("A6AB29C0703493A9A615EB8E41610607C") && ) {
//			//appid不对
//			logger.info("sdk_jh appid error " + orderNo);
//			returnInfo("fail", resp);
//			return;
//		}
		
		orders o = ordersDao.getOrderByMyorderid(orderNo);
		if(o == null) {
			//订单不存在
			logger.info("sdk_jh no order " + orderNo);
			returnInfo("fail", resp);
			return;
		}
		
		if(o.getOrderstate() == OrderInfoModule.orderinfofinish) {
			//订单已完成
			logger.info("sdk_jh order finished " + orderNo);
			returnInfo("ok", resp);
			return;
		}
		
		if(o.getOrderstate() == OrderInfoModule.orderinfofinish) {
			//订单失败
			logger.info("sdk_jh order fail " + orderNo);
			returnInfo("fail", resp);
			return;
		}
		
//		交易最终结果以 MD5 方式签名，签名算法如下（只需参数值参与签名）： 
//		sign= MD5(orderNo + userName + result + amount + pay_time + pay_channel + openKey)
//		String newsignstr = orderNo + userName + result + amount + pay_time + pay_channel + "918e6a95e7ff532a7db0794674d1c535";
		String newsignstr = orderNo + userName + result + amount + pay_time + pay_channel + openkey;
		
		logger.info("sdk_jh newsignstr:" + newsignstr);
		String newsign = HttpUtil.getMD5(newsignstr).toLowerCase();
		
		logger.info("sdk_jh newsign:" + newsign);
		logger.info("sdk_jh    sign:" + sign);
		
		if(!newsign.equals(sign)) {
			//TODO: 签名错误
			logger.info("sdk_jh sign error " + orderNo);
			returnInfo("fail", resp);
			return;
		}
		
		if(result == fail) {
			o.setOrderstate(OrderInfoModule.orderinfofail);
			ordersDao.update(o);
			//订单失败
			logger.info("sdk_jh order fail " + orderNo);
			returnInfo("fail", resp);
			return;
		}
		
		double dpayamount = Double.valueOf(amount) * 100;
		int payamount = (int) dpayamount;
		
		o.setPlatorderid(payNo);
		o.setUpdatetime(new Date());
		o.setPayamount(payamount);

		if(orderType == 2) {
			o.setSubchannel(pay_channel);
		}else {
			o.setSubchannel(o.getChannel());
		}
		
		o.setOrderstate(OrderInfoModule.orderinfofinish);
		ordersDao.update(o);
		
		ActType at = ActType.getat(o.getActtype());
//		PayType pt = PayType.getpt(at.getPaytype());
		PayMoudle_jh am = new PayMoudle_jh();
		ArrayList<Currency> curs = am.getRewardInfoByType(o.getPlayercode(), at, o.getGoodsid());
		
		charge charge = DataCenter.getData(o.getGoodsid(), charge.class);
		am.createOrderInfoModule(o, curs, charge.getVipexp(), o.getGoodsprice());
		
		returnInfo("ok", resp);
	}

	/**
	 * 返回信息到渠道
	 * 
	 * @param data
	 * @param resp
	 */
	public void returnInfo(String data, HttpServletResponse resp) {
		PrintWriter pw = null;
		resp.addHeader("Access-Control-Allow-Origin", "*");

		try {
			pw = resp.getWriter();
			pw.write(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pw != null)
				pw.close();
		}
	}

	@Override
	public String getChannel() {
		return SdkChannel.sdk_jh;
	}
	
}
